package com.xplay.xpocker.service.mahjong.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xplay.xpocker.entity.RoomInfoVO;
import com.xplay.xpocker.entity.room.ERoomHistoryFraction;
import com.xplay.xpocker.entity.room.ERoomUser;
import com.xplay.xpocker.entity.system.SysUser;
import com.xplay.xpocker.entity.system.UserVO;
import com.xplay.xpocker.mapper.CrRoomInfoMapper;
import com.xplay.xpocker.mapper.ERoomHistoryFractionMapper;
import com.xplay.xpocker.service.mahjong.IRoomHistoryService;
import com.xplay.xpocker.util.Decide;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.annotation.ApplicationScope;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wanjie
 * @date 2021/6/4 0:14
 */
@Service
public class RoomHistoryServiceImpl implements IRoomHistoryService {
    @Autowired
    @Resource
    private CrRoomInfoMapper roomInfoMapper;
    @Autowired
    @Resource
    private ERoomHistoryFractionMapper eRoomHistoryFractionMapper;

    @Override
    public IPage<RoomInfoVO> queryUserHistoryRoom(Page<RoomInfoVO> pageInfo, Integer userId) {
        IPage<RoomInfoVO> roomPage = roomInfoMapper.queryUserHistoryRoom(pageInfo, userId);
        List<RoomInfoVO> records = roomPage.getRecords();
        if (Decide.isEmpty(records)) {
            return null;
        }
        for (RoomInfoVO record : records) {
            List<UserVO> userVOS = new ArrayList<>();
            List<ERoomUser> users = new ERoomUser().selectList(new LambdaQueryWrapper<ERoomUser>().eq(ERoomUser::getRoomId, record.getRoomId()));
            for (ERoomUser user : users) {
                SysUser sysUser = new SysUser().selectById(user.getUserId());
                UserVO vo = new UserVO();
                vo.setUsername(sysUser.getUsername());
                vo.setPortraitUrl(sysUser.getPortraitUrl());
                vo.setFraction(eRoomHistoryFractionMapper.getUserFractionByRoomId(user.getUserId(), record.getRoomId()));
                userVOS.add(vo);
            }
            record.setUsers(userVOS);
        }
        return roomPage;
    }
}
